package com.mini.common.web.utils;

import com.mini.common.web.exception.BusinessException;
import com.mini.common.core.constant.HeaderConstants;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 上下文工具类
 * @author Zhou Feng
 */
public class ContextHolderUtils {

    public static UserInfo getCurrentUserInfo() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        if (request==null){
            throw new BusinessException("服务错误");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(Long.parseLong(request.getHeader(HeaderConstants.HEADER_UID)));
        userInfo.setUsername(request.getHeader(HeaderConstants.HEADER_USERNAME));
        userInfo.setNickname(request.getHeader(HeaderConstants.HEADER_NICKNAME));
        return userInfo;
    }

    @Data
    @NoArgsConstructor
    public static class UserInfo {
        private long uid;
        private String username;
        private String nickname;
    }
}
